/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.imsx.controller.util;

import javax.faces.context.FacesContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author mivkys
 */
public class Cookies {

    public Cookies() {
    }
    
    public void setCookie(String nombre, String value,int expiracion) {

    FacesContext facesContext = FacesContext.getCurrentInstance();

    HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
    Cookie cookie = null;

    Cookie[] userCookies = request.getCookies();
    if (userCookies != null && userCookies.length > 0 ) {
        for (Cookie userCookie : userCookies) {
            if (userCookie.getName().equals(nombre)) {
                cookie = userCookie;
                break;
            }
        }
    }

    if (cookie != null) {
        cookie.setValue(value);
    } else {
        cookie = new Cookie(nombre, value);
        cookie.setPath(request.getContextPath());
    }

    cookie.setMaxAge(expiracion);

    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
    response.addCookie(cookie);
}

public String getCookie(String nombre) {

    FacesContext facesContext = FacesContext.getCurrentInstance();

    HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
    Cookie cookie = null;

    Cookie[] userCookies = request.getCookies();
    if (userCookies != null && userCookies.length > 0 ) {
        for (Cookie userCookie : userCookies) {
            if (userCookie.getName().equals(nombre)) {
                cookie = userCookie;
                return cookie.getValue();
            }
        }
    }
    return null;
}
}
